package com.earnings.okhttputils.utils.view;

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * Created by Administrator on 2017/6/16 0016.
 */

public class AutoSizeWebView extends WebView {
    private AutoSizeWebView.OnHeightChangeListener onHeightChangeListener;

    public AutoSizeWebView(Context context) {
        super(context);
        this.init();
    }

    public AutoSizeWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.init();
    }

    public AutoSizeWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.init();
    }

    private void init() {
        this.getSettings().setJavaScriptEnabled(true);
        this.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                int w = MeasureSpec.makeMeasureSpec(0, 0);
                int h = MeasureSpec.makeMeasureSpec(0, 0);
                AutoSizeWebView.this.measure(w, h);
                if (AutoSizeWebView.this.onHeightChangeListener != null) {
                    AutoSizeWebView.this.onHeightChangeListener.onHeightChange(AutoSizeWebView.this, AutoSizeWebView.this.getMeasuredHeight());
                }

            }
        });
    }

    public void setOnHeightChangeListener(AutoSizeWebView.OnHeightChangeListener onHeightChangeListener) {
        this.onHeightChangeListener = onHeightChangeListener;
    }

    public interface OnHeightChangeListener {
        void onHeightChange(WebView var1, int var2);
    }
}
